<template>
  <div id="editor-passage">
    <el-row>
      <el-col :lg="18" :sm="18" :xs="12" style="text-align: left; font-size: 30px">编辑游记</el-col>
      <el-col :lg="6" :sm="6" :xs="12" style="margin: auto">
        <el-button @click="save">保存草稿</el-button>
        <el-button plain @click="publish = true"> 发布</el-button>
        <el-dialog v-model="publish" title="添加游记分类信息，帮助更多人" width="700" center>
          <el-form
            ref="ArticleRef"
            :rules="ArticleRule"
            :model="diary"
            label-width="auto"
            style="width: 100%; margin: 0 auto"
          >
            <div class="form-header" style="display: flex; align-items: center; gap: 8px">
              <el-icon size="30px" color="orange">
                <PriceTag />
              </el-icon>
              <span>旅游目的地</span>
            </div>
            <el-form-item label="旅游地点" prop="destination">
              <el-input v-model="diary.destination" placeholder="请输入国家/城市" />
            </el-form-item>
            <div class="form-header" style="display: flex; align-items: center; gap: 8px">
              <el-icon size="30px" color="orange">
                <PriceTag />
              </el-icon>
              <span>更多信息</span>
            </div>
            <el-form-item label="行程天数" prop="durationsDays">
              <el-input v-model.number="diary.durationsDays" placeholder="天数" />
            </el-form-item>
            <el-form-item label="人均消费" prop="costPerPerson">
              <el-input v-model.number="diary.costPerPerson" placeholder="花费" />
            </el-form-item>
            <el-form-item label="出发时间" prop="departureDate">
              <el-date-picker
                v-model="diary.departureDate"
                type="date"
                placeholder="选择出发时间"
                clearable
              />
            </el-form-item>
            <el-form-item label="标签" prop="tag">
              <el-input-tag v-model="diary.tags" :max="3" placeholder="最多输入三个标签" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="publish = false">取消</el-button>
              <el-button type="primary" @click="submitPutArticle"> 确认</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
    <el-row>
      <el-col :lg="17" :xs="24">
        <el-row>
          <div id="editor-title" style="width: 100%; display: flex; align-items: center; gap: 8px">
            <el-icon size="45px" color="orange">
              <Edit />
            </el-icon>
            <el-input
              v-model="diary.title"
              placeholder="游记标题"
              style="height: 50px; font-size: 18px"
              >{{ diary.title }}
            </el-input>
          </div>
        </el-row>
        <el-row>
          <!-- 编辑内容部分 -->
          <div id="editor-content"></div>
        </el-row>
      </el-col>
      <el-col :offset="1" :lg="6" :xs="24">
        <el-row style="width: 100%">
          <div class="catalog" style="width: 100%">
            <el-card style="height: 250px; width: 100%">
              <template #header>
                <div class="card-header" style="display: flex; align-items: center; gap: 8px">
                  <el-icon size="30px" color="orange">
                    <PriceTag />
                  </el-icon>
                  <span>游记目录</span>
                </div>
              </template>
              <p>暂无目录</p>
            </el-card>
          </div>
        </el-row>
        <el-row style="width: 100%">
          <div class="cover-image" style="width: 100%">
            <el-card style="height: 320px">
              <template #header>
                <div class="card-header" style="display: flex; align-items: center; gap: 8px">
                  <el-icon size="30px" color="orange">
                    <Picture />
                  </el-icon>
                  <span style="margin: 5px">封面图上传</span>
                </div>
              </template>
              <el-upload
                class="upload-demo"
                multiple
                drag
                :auto-upload="true"
                :http-request="customUpload"
              >
                <el-icon class="el-icon--upload">
                  <upload-filled />
                </el-icon>
                <div class="el-upload__text">拖拽至此或者<em>点击上传</em></div>
                <!-- <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500kb
                </div>
              </template> -->
              </el-upload>
            </el-card>
          </div>
        </el-row>
        <el-row style="width: 100%; display: flex; justify-content: center">
          <el-button @click="save" :onload="draftLoading">保存草稿</el-button>
          <el-button plain @click="publish = true" :onload="publishLoading"> 发布</el-button>
        </el-row>
      </el-col>
    </el-row>
    <!-- 提交时显示进度条 -->
    <!-- 全屏遮罩进度条 -->
    <div v-if="loading" class="progress-overlay">
      <div class="progress-content">
        <el-progress
          :text-inside="true"
          :stroke-width="18"
          :percentage="progress"
          status="success"
        />
        <!--        <el-progress-->
        <!--          :percentage="progress"-->
        <!--          status="active"-->
        <!--          :stroke-width="18"-->
        <!--          type="circle"-->
        <!--          :width="120"-->
        <!--        />-->
        <p style="margin-top: 12px">正在提交游记...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defaultConfig } from '@/utils/config/markdownDefaultConfig.js'
import { onMounted, reactive } from 'vue'
import type { Article } from '@/utils/dataType/ArticleModel'

import { ref } from 'vue'
import { putDraftArticle, putPublishArticle, uploadImage } from '@/services/api/passage'
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus'
import { formatDate } from '@/utils/commonMessage/common'
import myAxios from '@/utils/config/axiosConfig.ts'
import router from '@/router'

const publish = ref(false)
const draftLoading = ref(false)
const publishLoading = ref(false)

const diary = reactive<Article>({
  title: '',
  content: '这是初始化内容',
})

let editor: any = null

function getConfig() {
  // defaultConfig.markdown = diary.content
  // defaultConfig.onchange = () => {
  //   if (editor) {
  //     diary.content = editor.getMarkdown()
  //   }
  // }
  // return defaultConfig
  return {
    markdown: diary.content, // 这里直接访问 reactive 对象的属性
    width: '100%',
    height: 480,
    path: '/lib/editor.md/lib/', // 替换为你的编辑器路径
    imageUpload: true,
    imageUploadURL: myAxios.defaults.baseURL + '/user/article/image',
    saveHTMLToTextarea: true,
    crossDomainUpload:true,
    imageFormats: ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'webp'],
    onchange: () => {
      if (editor) {
        diary.content = editor.getMarkdown() // 更新 reactive 对象的 content 属性
      }
    },
  }
}

//验证发布的内容
const ArticleRef = ref<FormInstance>()
const ArticleRule = ref<FormRules<Article>>({
  destination: [{ required: true, message: '请输入目的地', trigger: 'blur' }],
  durationsDays: [{ required: true, message: '请输入行程天数', trigger: 'blur' }],
  departureDate: [{ required: true, message: '请输入出发时间', trigger: 'blur' }],
  costPerPerson: [{ required: true, message: '请输入人均消费', trigger: 'blur' }],
  tags: [{ required: true, message: '请输入标签', trigger: 'blur' }],
})

function checkTitleAndContent() {
  if (
    diary.content == null ||
    diary.content.length == 0 ||
    diary.title == null ||
    diary.title.length == 0
  ) {
    return false
  } else {
    return true
  }
}

function save() {
  diary.content = editor.getMarkdown()
  if (checkTitleAndContent()) {
    const article: Article = {
      title: diary.title,
      content: diary.content,
    }
    saveDraft(article)
  } else {
    ElMessage.error('有内容未填写')
  }
}

//进度条展示
const progress = ref(0)
const loading = ref(false)

async function saveDraft(article: Article) {
  loading.value = true
  progress.value = 0
  const timer = setInterval(() => {
    if (progress.value < 90) progress.value += 5
  }, 200)
  try {
    const res = await putDraftArticle(article)
    if (res.code !== 1) {
      throw new Error('提交失败:' + res.msg)
    }
    clearInterval(timer)
    progress.value = 100
    // setTimeout(() => {
    //   ElMessage.success('保存成功！正在跳转...')
    // }, 500)
    loading.value = false
    progress.value = 0
    ElMessage.success('保存草稿成功！正在跳转...')
    setTimeout(() => {
      router.push({
        path: '/handleEvent',
        query: {
          message: 'success',
        },
      })
    }, 500)
    // ElMessage.success('保存草稿成功')
  } catch (error) {
    loading.value = false
    progress.value = 0
    router.push({
      path: 'handleEvent',
      query: {
        message: error,
      },
    })
    console.error('保存草稿出错:', error)
  }
}

async function publishArticle(article: Article) {
  // try {
  //   const res = await putPublishArticle(article)
  //   ElMessage.success('提交文章成功,请等待审核')
  // } catch (error) {
  //   console.error('提交文章失败:', error)
  // }
  loading.value = true
  progress.value = 0
  const timer = setInterval(() => {
    if (progress.value < 90) progress.value += 5
  }, 200)
  try {
    const res = await putPublishArticle(article)
    if (res.code !== 1) {
      throw new Error('提交失败:' + res.msg)
    }
    clearInterval(timer)
    progress.value = 100
    // setTimeout(() => {
    //   ElMessage.success('保存成功！正在跳转...')
    // }, 500)
    loading.value = false
    progress.value = 0
    ElMessage.success('提交文章成功!请等待审核!正在跳转...')
    setTimeout(() => {
      router.push({
        path: '/handleEvent',
        query: {
          message: 'success',
        },
      })
    }, 500)
    // ElMessage.success('保存草稿成功')
  } catch (error) {
    loading.value = false
    progress.value = 0
    router.push({
      path: 'handleEvent',
      query: {
        message: 'error',
      },
    })
    console.error('提交文章出错:', error)
  }
}

function submitPutArticle() {
  if (!ArticleRef.value) return
  ArticleRef.value.validate((valid) => {
    if (valid) {
      if (!checkTitleAndContent()) {
        ElMessage.error('有正文未填写')
      } else {
        diary.departureDate = formatDate(diary.departureDate) //格式化时间
        const article = diary
        publishArticle(article)
      }
    }
  })
}

const customUpload: UploadProps['httpRequest'] = async (options) => {
  try {
    console.log('尝试上传图片')
    console.log(options.file)
    const formData = new FormData()
    formData.append('file', options.file)
    const res = await uploadImage(formData)
    diary.pic = res.data
    ElMessage.success('文件上传成功')
    options.onSuccess(res.data)
  } catch (error) {
    console.error('封面图上传失败:', error)
    options.onError(error)
  }
}

// const handleSingleUpload: UploadProps['httpRequest'] = async (options) => {
//   console.log('尝试上传图片')
//   console.log(options.file)
//   const formData = new FormData()
//   formData.append('file', options.file)
//   ElMessage.success('开始上传图片')
//   try {
//     const res = await uploadImage(formData)
//     if (res.code !== 1) throw new Error('上传失败')
//     if (res.data) {
//       const oldContent = editor.getMarkdown() // 获取当前内容
//       const newContent = oldContent + `![](${res.data})\n`
//       editor.setMarkdown(newContent) // 重新设置内容
//       // editor.insertValue(`![](${res.data})\n`)
//       diary.content = newContent
//       options.onSuccess(res.data)
//     } else {
//       options.onError(new Error(res.msg || '上传接口返回失败'))
//     }
//   } catch (error) {
//     ElMessage.error('图片上传失败')
//     options.onError(error)
//   }
// }

onMounted(() => {
  editor = editormd('editor-content', getConfig())
})
</script>

<style scoped>
#editor-passage {
  width: 85%;
  margin: 20px auto;
}

.el-row {
  margin-bottom: 25px;
}

.el-card .card-header {
  font-size: 20px;
  text-align: left;
}

.el-form .form-header {
  margin-bottom: 20px;
}

.progress-overlay {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  width: 100vw;
  height: 100vh;
  backdrop-filter: blur(4px); /* 背景虚化 */
  background-color: rgba(0, 0, 0, 0.3); /* 半透明遮罩 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.progress-content {
  text-align: center;
  color: white;
}
</style>
